using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace FrameRateCounterComponent
{
    /// <summary>
    /// Displays the FPS
    /// </summary>
    public class FrameRateCounter : DrawableGameComponent
    {
        private TimeSpan _elapsedTime = TimeSpan.Zero;
        private int _frameCounter;
        private int _frameRate;
        private SpriteBatch _spriteBatch;
        private SpriteFont _font;
        private ContentManager _content;
        private GraphicsDevice _graphicsDevice;

        public FrameRateCounter(Game game)
            : base(game)
        {
            _content = game.Content;
            _graphicsDevice = game.GraphicsDevice;
        }

        protected override void LoadContent()
        {
            _font = _content.Load<SpriteFont>("System");

            _spriteBatch = new SpriteBatch(GraphicsDevice);
            
            base.LoadContent();
        }


        public override void Update(GameTime gameTime)
        {
            _elapsedTime += gameTime.ElapsedGameTime;

            if (_elapsedTime <= TimeSpan.FromSeconds(1)) return;

            _elapsedTime -= TimeSpan.FromSeconds(1);
            _frameRate = _frameCounter;
            _frameCounter = 0;
        }

        public override void Draw(GameTime gameTime)
        {
            _frameCounter++;

            string fps = _frameRate.ToString();

            _spriteBatch.Begin();
            _spriteBatch.DrawString(_font, "FPS: " + fps, new Vector2(900, 10), Color.White);
            _spriteBatch.End();
        }
    }
}